package com.obrempon.credit.market.common

import android.Manifest
import android.content.Intent
import android.net.Uri
import android.view.View
import com.obrempon.credit.market.ObremponApp
import com.obrempon.credit.market.R
import com.obrempon.credit.market.base.BaseActivity
import com.obrempon.credit.market.event.ObremponEventData
import com.obrempon.credit.market.event.ObremponEventPointHelper
import com.obrempon.credit.market.event.ObremponEventPointType
import com.obrempon.credit.market.event.ObremponEventSubscriber
import com.obrempon.credit.market.request.HttpHelper
import com.obrempon.credit.market.request.IHttpCallback
import com.obrempon.credit.market.ui.dialog.ObremponCustomerDialog
import com.obrempon.credit.market.ui.dialog.ObremponTipsDialog
import com.obrempon.credit.market.utils.log.ObremponLogger
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.MainScope
import org.json.JSONObject
import pub.devrel.easypermissions.AppSettingsDialog
import pub.devrel.easypermissions.EasyPermissions

/**
 * CommonActivity
 * @Author wwdeng
 * @CreateTime: 2024/11/20 10:32
 * @Annotation：
 */
abstract class CommonActivity: BaseActivity(), ObremponEventSubscriber,ICommonView, CoroutineScope by MainScope(),EasyPermissions.PermissionCallbacks {
    private val PERMISSION_CALL_PHONE_CODE = 10001;
    private var callMobile = ""

    var errorDialog: ObremponTipsDialog? = null

    override fun getAct(): CommonActivity {
        return this
    }

    override fun onStart() {
        super.onStart()
//        HttpHelper.setTag(this)
        ObremponApp.app.publisher.register(this)
    }

    /**
     * 错误提示
     */
    fun showErrorTipsDialog(tips: String,eventRemark: String = ""){
        if (errorDialog == null){
            errorDialog = ObremponTipsDialog(this,eventRemark)
        }
        if (errorDialog!!.isShowing){
            return
        }
        errorDialog?.setOnClick(object : ObremponTipsDialog.IDialogCallback{
            override fun onClick(view: View?) {

            }
        })
        errorDialog?.show()
        errorDialog?.isObremponKindTipsDoubleButton(false)
        errorDialog?.setObremponKindTipsMsgText(tips)
    }

    /**
     * 客服
     */
    fun showCustomerDialog(eventRemark: String = "",pName: String = "", pToken: String = ""){
        ObremponCustomerDialog(this)
            .setCustomerCancelable(true)
            .setCustomerCanceledOnTouchOutside(true)
            .setCustomerProductName(pName)
            .setCustomerProductToken(pToken)
            .setCustomerEventRemark(eventRemark)
            .setCustomerClickCallback(object : ObremponCustomerDialog.IDialogCallback{
                override fun onObremponCallPhoneClick(phoneNumber: String) {
                    if (EasyPermissions.hasPermissions(getContext(), Manifest.permission.CALL_PHONE)) {
                        onCustomerMobileCallAction(phoneNumber)
                    } else {
                        callMobile = phoneNumber
                        EasyPermissions.requestPermissions(this@CommonActivity,"",PERMISSION_CALL_PHONE_CODE,Manifest.permission.CALL_PHONE)
                    }
                }
                override fun onObremponCopyEmailClick(email: String) {
                }
            })
            .show()
    }

    /**
     * 接口请求失败提示
     */
    fun showRequestErrorDialog(errorData: JSONObject){
        if (errorDialog == null){
            errorDialog = ObremponTipsDialog(this)
        }
        if (errorDialog!!.isShowing){
            return
        }
        errorDialog?.setOnClick(object : ObremponTipsDialog.IDialogCallback{
            override fun onClick(view: View?) {
                if (view?.id == R.id.buttonConfirm){
                    requestTryAgain()
                }
            }
        })
        errorDialog?.addObremponKindTipsEventRemark("network error")
        errorDialog?.setCancelable(true)
        errorDialog?.setCanceledOnTouchOutside(false)
        errorDialog?.show()
        errorDialog?.isObremponKindTipsDoubleButton(true)
        errorDialog?.setObremponKintTipsButtonConfirmText(getString(R.string.obrempon_button_try_again))
        errorDialog?.setObremponKindTipsMsgText(getString(R.string.obrempon_dialog_network_error))
    }

    /**
     * post
     */
    fun doPostAction(httpUrl: String,params: JSONObject,callback: IHttpCallback){
        HttpHelper.post(httpUrl,params,object : IHttpCallback{
            override fun onRequestSuccess(data: JSONObject) {
                callback.onRequestSuccess(data)
            }

            override fun onRequestError(error: JSONObject) {
                callback.onRequestError(error)
                showObremponToast(error.optString("errorMsg"))
            }

            override fun onRequestFinish() {
                callback.onRequestFinish()
            }
        })
    }

    /**
     * 添加埋点
     */
    fun addEventPointRequestAction(eventName: String, eventRemark: String? = "") {
        ObremponEventPointHelper.addEventPointRequestAction(eventName,eventRemark)
    }

    /**
     * 发送事件通知
     */
    fun publishEventData(eventData: ObremponEventData){
        ObremponApp.app.publisher.publish(eventData)
    }

    /**
     * 处理订阅事件
     */
    override fun onObremponPublishEvent(event: ObremponEventData) {
    }

    /**
     * 重试
     */
    override fun requestTryAgain() {
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        // 进一步使用 EasyPermissions 处理后续结果
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    /**
     * 用户点击同意授权后会回调该方法
     */
    override fun onPermissionsGranted(requestCode: Int, perms: MutableList<String>) {
        ObremponLogger.e("onPermissionsGranted, code: $requestCode , permissions : $perms")
        if (requestCode == PERMISSION_CALL_PHONE_CODE){
            addEventPointRequestAction(ObremponEventPointType.CLICK.OBREMPON_CLICK_PERMISSION_SYSTEM_AGREE,perms[0])
            onCustomerMobileCallAction(callMobile)
        }
    }

    /**
     * 用户点击拒绝授权后会回调该方法
     */
    override fun onPermissionsDenied(requestCode: Int, perms: MutableList<String>) {
        ObremponLogger.e("onPermissionsDenied code: $requestCode , permissions : $perms")
        if (requestCode == PERMISSION_CALL_PHONE_CODE){
            addEventPointRequestAction(ObremponEventPointType.CLICK.OBREMPON_CLICK_PERMISSION_SYSTEM_DENY, perms[0])
            // 如果申请的权限中有任何一个权限存在 永久拒绝 的情况
            if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
                // 设置 引导用户前往设置界面 自行设置权限的引导对话框
                AppSettingsDialog.Builder(this)
//                .setTitle("需要手动设置权限")
//                .setRationale("存在永久拒绝的权限 , 需要手动前往设置界面为应用进行授权")
//                .setPositiveButton("前往设置界面")
//                .setNegativeButton("不使用该功能")
                    .build().show()
            }
        }
    }

    /**
     * 拨号
     */
    private fun onCustomerMobileCallAction(mobile: String){
        ObremponEventPointHelper.addEventPointRequestAction(ObremponEventPointType.CLICK.OBREMPON_CLICK_KEFU_DIAL, "Mobile ：$mobile")
        val callIntent = Intent(Intent.ACTION_DIAL)
        callIntent.setData(Uri.parse("tel:$mobile"))
        startActivity(callIntent)
    }

    override fun onDestroy() {
        super.onDestroy()
        HttpHelper.cancelTag(this)
        ObremponApp.app.publisher.detach(this)
    }
}